//
//  PlaceOrderViewController.m
//  HAODE
//
//  Created by LiYinDi on 16/1/11.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "PlaceOrderViewController.h"
#import "PlaceOrderProductListViewController.h"
#import "RDVTabBarController.h"
#import "HttpRequest.h"
#import "TheLoginViewController.h"
#import "BusinessCheckVouchContinueViewController.h"
#import "SelectedGoodNewViewController.h"
#import "OrderExtAddViewController.h"
#import "WhsInAddViewController.h"
#import "ProductDetailViewController.h"

#import "FMDB.h"
#import "NoSpecFmdbTool.h"
#import "LeftJoinFmdbModel.h"
#import "fmDataModel.h"
#import "ReabamSingleton.h"
#import "SelectedGoodNewViewController1.h"
//>>>>>>>???
@interface PlaceOrderViewController ()<PlaceOrderProductListDelegate>
{
    UITextField *searchTextField;
    NSMutableArray *totalDataArray;
    NSMutableArray *parentTypeArray;
    NSString *userToken;
    
    ReabamSingleton*commdity;
    NSMutableArray *labelArray;
}

@end

@implementation PlaceOrderViewController
@synthesize alt = alt;
-(void)viewWillAppear:(BOOL)animated
{
   
    [self setNavigation];
    [super viewDidLoad];
 
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.saveTypeStr=[Global getType];
    self.ptype=[Global getPlaceOrderPType];
   
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];
   
    commdity=[ReabamSingleton shared];
    self.memberDict=commdity.dataMemberDict;
    parentTypeArray=[NSMutableArray array];
    labelArray=[NSMutableArray array];
    [self requestProductType];
   
    self.dataSource = self;
    self.delegate = self;


}
-(void)requestProductType
{
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:userToken forKey:@"tokenId"];
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"Business/Order/ProductTypes" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                //               NSLog(@"severdata11===%@",severDataDict.dataDict);
               
                totalDataArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                
                
                for (int i=0;i<totalDataArray.count;i++)
                {
                    [parentTypeArray addObject:[[totalDataArray objectAtIndex: i] valueForKey:@"ParentName"]];
                    
                }
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:parentTypeArray forKey:@"parentTypeName"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self reloadData];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    
//                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
//                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
    
}
#pragma mark - ViewPagerDataSource
- (NSUInteger)numberOfTabsForViewPager:(ViewPagerController *)viewPager {
    
    if (parentTypeArray.count>0) {
        return parentTypeArray.count;
    }
    else
        return 0;
}
- (UILabel *)viewPager:(ViewPagerController *)viewPager viewForTabAtIndex:(NSUInteger)index {
    
    
    if (parentTypeArray.count>0) {
        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:15.0];
        
        label.text = [NSString stringWithFormat:@"%@",[parentTypeArray objectAtIndex:index]];
//        NSLog(@"[parentTypeArray objectAtIndex:index]===%@",[parentTypeArray objectAtIndex:index]);
       
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
        [label sizeToFit];
        [labelArray addObject:label];
        
        return label;
    }
    else
    {
        return  nil;
    }
}
- (UIViewController *)viewPager:(ViewPagerController *)viewPager contentViewControllerForTabAtIndex:(NSUInteger)index {
    
    
//    [labelArray replaceObjectAtIndex:index withObject:label];
    PlaceOrderProductListViewController *cvc = [[PlaceOrderProductListViewController alloc] init];
    NSMutableArray *dataArray=[NSMutableArray arrayWithArray:[[totalDataArray objectAtIndex:index] objectForKey:@"TypeList"]];
    cvc.titleString=[parentTypeArray objectAtIndex:index];
    cvc.typeString=self.saveTypeStr;
    cvc.saveTypeStr=self.saveTypeStr;
    cvc.ptype=_ptype;
    cvc.memberDict=self.memberDict;
//    NSLog(@"cvc.titleString===%@",cvc.titleString);
    cvc.parentDataArray=[NSMutableArray arrayWithArray:dataArray];
    cvc.delegate=self;
    
    return cvc;
}

#pragma mark - ViewPagerDelegate
- (UIColor *)viewPager:(ViewPagerController *)viewPager colorForComponent:(ViewPagerComponent)component withDefault:(UIColor *)color {
    
    switch (component) {
        case ViewPagerIndicator:
            return [UIColor colorWithRed:90.0/255.0 green:130.0/255.0 blue:26.0/255.0 alpha:1.0];//[[UIColor redColor] colorWithAlphaComponent:0.64];
            break;
        default:
            break;
    }
    
    return color;
}
- (void)viewPager:(ViewPagerController *)viewPager didChangeTabToIndex:(NSUInteger)index
{
    
    if (labelArray.count>0) {
        for (int i=0;i<labelArray.count;i++ ) {
        UILabel *label=(UILabel *)[labelArray objectAtIndex:i];
        label.textColor=[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
    }
    UILabel *label=(UILabel *)[labelArray objectAtIndex:index];
    //     NSLog(@"index^^^^^===%d",index);
    label.textColor=[UIColor blackColor];
        
    }
}
-(void)selectedGoodsBtnClick
{
    
     if ([self.saveTypeStr isEqualToString:@"SCANCASHIER"]) {
    
         SelectedGoodNewViewController1 *selectedGoodVC=[[SelectedGoodNewViewController1 alloc] init];//2.0{9个参数 少2个}
         selectedGoodVC.memberDict=self.memberDict;
         selectedGoodVC.typeString=self.saveTypeStr;
         [self.navigationController pushViewController:selectedGoodVC animated:YES];

     
     }else{
    
    
    SelectedGoodNewViewController *selectedGoodVC=[[SelectedGoodNewViewController alloc] init];//2.0{9个参数 少2个}
    selectedGoodVC.typeString=self.saveTypeStr;
        //下面继续盘点的带出来的数据
        selectedGoodVC.ckvId=self.ckvId;
        selectedGoodVC.ckvNo=self.ckvNo;
        selectedGoodVC.whsName=self.whsName;
        selectedGoodVC.itemTypeName=self.itemTypeName;
        selectedGoodVC.whsId=self.whsId;
        selectedGoodVC.itemTypeCode=self.itemTypeCode;
    [self.navigationController pushViewController:selectedGoodVC animated:YES];
     }
}
-(void)subTableViewCellCliCK:(NSString *)itemIdString
{
//    ProductDetailViewController *detailViewController = [[ProductDetailViewController alloc] init];
//    detailViewController.itemIdStr=itemIdString;
//    
//    detailViewController.saveTypeStr=self.Whs;
//    
//    detailViewController.typeString=self.Whs;
//    //下面继续盘点的带出来的数据
//    
//    
//    detailViewController.ckvId=self.ckvId;
//    detailViewController.ckvNo=self.ckvNo;
//    detailViewController.whsName=self.whsName;
//    detailViewController.itemTypeName=self.itemTypeName;
//    detailViewController.whsId=self.whsId;
//    detailViewController.itemTypeCode=self.itemTypeCode;
//    [self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark delegate
-(void)loginAgain
{
    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
    [self.navigationController pushViewController:loginVC animated:YES];

}
-(fmDataModel *)getDataFromFM
{
    NSArray *resultArray= [NoSpecFmdbTool queryLeftJoin:self.saveTypeStr userToken:userToken];
    fmDataModel *fmModel=[fmDataModel dataModelWithArray:[resultArray mutableCopy]];
    return fmModel;
}

-(void)confirmSubmit
{
    
    
    if ([self.saveTypeStr isEqualToString:@"SCANCASHIER"]) {
    
        [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:userToken forKey:@"tokenId"];
        [HttpRequest requestData:@"Business/ShopCart/Confirm" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
//                    NSLog(@"------%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"totalQty"] integerValue]==0) {
                        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                        [alertView show];

                    }else{
                    OrderExtAddViewController *shouyinVC=[[OrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
                    shouyinVC.dataDictionary=severDataDict.dataDict;
                    shouyinVC.saveTypeStr=self.saveTypeStr;
                    shouyinVC.orderType=@"order";
                    shouyinVC.OrderSat=@"Order/Add";
                    shouyinVC.memberDict=commdity.dataMemberDict;
                    [self.navigationController pushViewController:shouyinVC animated:YES];
                    }
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    
                }
                
            }else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }];

    
       }else{
    
    
    
    
    fmDataModel *model=  [self getDataFromFM];
    if (model.productItemCodeArray.count>0) {
       if ([self.saveTypeStr isEqualToString:@"WhsOut"]||[self.saveTypeStr isEqualToString:@"WhsIn"]||[self.saveTypeStr isEqualToString:@"CheckVouch"]||[self.saveTypeStr isEqualToString:@"NeedOrder"]||[self.saveTypeStr isEqualToString:@"Allot"]||[self.saveTypeStr isEqualToString:@"Refund"]) {
            WhsInAddViewController *detailViewController = [[WhsInAddViewController alloc] init];
        
            detailViewController.saveTypeStr=self.saveTypeStr;
            detailViewController. itemCodeArray=model.productItemCodeArray;
            detailViewController. itemIdArray=model.productIDArray;
            detailViewController. itemNameArray=model.productNameArray;
            detailViewController. headImageFullArray=model.productImageArray;
            detailViewController. dealPriceArray=model.productPriceArray;
            detailViewController. specIdArray=model.productSpecIDArray;
            detailViewController. quantityArray=model.productCountArray;
            detailViewController. specNameArray=model.productSpecNameArray;
           
           NSLog(@"model.productPriceArrayin====%@",model.productPriceArray);
           NSLog(@"model.productCountArrayin====%@",model.productCountArray);

            [self.navigationController pushViewController:detailViewController animated:YES];
            
        }
        
        
        else if ([self.saveTypeStr isEqualToString:@"Continue"]) {
            
            BusinessCheckVouchContinueViewController *detailViewController = [[BusinessCheckVouchContinueViewController alloc] init];
            detailViewController.titleName=@"继续盘点";
            detailViewController.Whs=@"Continue";
            detailViewController.ckvId=self.ckvId;
            detailViewController.ckvNo=self.ckvNo;
            detailViewController.whsName=self.whsName;
            detailViewController.itemTypeName=self.itemTypeName;
            detailViewController.whsId=self.whsId;
            detailViewController.itemTypeCode=self.itemTypeCode;
            detailViewController.saveTypeStr=self.saveTypeStr;
            
            detailViewController. itemCodeArray=model.productItemCodeArray;
            detailViewController. itemIdArray=model.productIDArray;
            detailViewController. itemNameArray=model.productNameArray;
            detailViewController. headImageFullArray=model.productImageArray;
            detailViewController. dealPriceArray=model.productPriceArray;
            detailViewController. specIdArray=model.productSpecIDArray;
            detailViewController. quantityArray=model.productCountArray;
            detailViewController. specNameArray=model.productSpecNameArray;
            [self.navigationController pushViewController:detailViewController animated:YES];
        }
        
        
        
    }
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
       }
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
//  [[self rdv_tabBarController] setBlurViewHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0,100, 21)];
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.text=@"选择商品";
    
    self.navigationItem.titleView = titleLabel;
    
    self.navigationController.navigationBar.barStyle =UIBaselineAdjustmentNone ;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    
}

-(void)BackAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)requestProductDetail:(NSString *)codeStr
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:codeStr forKey:@"itemId"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Product/GetProductDetail" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
//                ProductDetailViewController *detailViewController = [[ProductDetailViewController alloc] init];
//                detailViewController.itemIdStr=codeStr;
//                detailViewController.itemIdStr=self.Whs;
//                
//                detailViewController.typeString=self.Whs;
//                //下面继续盘点的带出来的数据
//                //                 NSLog(@"self.Whs%@",self.Whs);
//                
//                detailViewController.ckvId=self.ckvId;
//                detailViewController.ckvNo=self.ckvNo;
//                detailViewController.whsName=self.whsName;
//                detailViewController.itemTypeName=self.itemTypeName;
//                detailViewController.whsId=self.whsId;
//                detailViewController.itemTypeCode=self.itemTypeCode;
//                
//                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
            else{
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }

            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}


@end
